package cn.smart.feign.decoder;
import cn.hutool.core.util.TypeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.smart.core.exception.BizException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class CustomResponseDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException {
        try {
            // 检查响应体是否为空
            if (response.body() == null) {
                throw new DecodeException(response.status(), "响应体为空", response.request());
            }
            // 将响应体转为字符串
            String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
            if (bodyStr == null || bodyStr.isEmpty()) {
                throw new DecodeException(response.status(), "响应体内容为空", response.request());
            }
            // 解析JSON为JSONObject
            JSONObject jsonObject = JSONUtil.parseObj(bodyStr, true);
            // 获取code并判断是否成功
            int code = JSONUtil.getByPath(jsonObject, "code", -1);
            if (code != 0) {
                String message = JSONUtil.getByPath(jsonObject, "msg", "未知错误").toString();
                BizException.throwBizException(code, message);
            }
            // 获取data字段
            Object data = JSONUtil.getByPath(jsonObject, "data");
            if (data == null) {
                return null;
            }
            // 获取返回类型
            Class<?> targetClass = TypeUtil.getClass(type);
            Object result;
            // 处理List类型
            if (targetClass.isAssignableFrom(List.class)) {
                Type typeArgument = TypeUtil.getTypeArgument(type);
                if (typeArgument == null) {
                    throw new DecodeException(response.status(), "无法解析List泛型类型", response.request());
                }
                Class<?> elementClass = TypeUtil.getClass(typeArgument);
                result = JSONUtil.toList(JSONUtil.toJsonStr(data), elementClass);
            } else if (targetClass == String.class) {
                // 特殊处理String类型
                result = data.toString();
            } else {
                // 其他类型直接转换
                result = JSONUtil.toBean(JSONUtil.toJsonStr(data), targetClass);
            }
            return result;
        } catch (Exception ex) {
            // 捕获所有异常，转换为DecodeException
            throw new DecodeException(response.status(), "Feign解析错误: " + ex.getMessage(), response.request(), ex);
        }
    }
}
